home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / ada / c01oop.zip / CPPWKBK / CPPV5-4.CPP < prev    next >
C/C++ Source or Header  |  1992-08-25  |  2KB  |  84 lines

  1. #define HEADER "C++ Problem 5.4 by Rick Conn using Borland C++"
  2.  
  3. #include <stdio.h>
  4.  
  5. // COMPLEX Class
  6. class complex {
  7.   float real_part;
  8.   float imag_part;
  9.   char *name;
  10. public:
  11.   complex (char *, float rp=0.0, float ip=0.0);
  12.   void set (float rp=0.0, float ip=0.0);
  13.   complex & operator= (complex &);
  14.   complex operator+ (complex &right);
  15.   complex operator- (complex &right);
  16.   complex operator* (complex &right);
  17.   void print(void);
  18. };
  19.  
  20. complex::complex (char *n, float rp, float ip) {
  21.   name = n;  real_part = rp;  imag_part = ip;
  22. }
  23.  
  24. void complex::set (float rp, float ip) {
  25.   real_part = rp;  imag_part = ip;
  26. }
  27.  
  28. complex & complex::operator= (complex &arg) {
  29.   real_part = arg.real_part;
  30.   imag_part = arg.imag_part;
  31.   return *this;
  32. }
  33.  
  34. complex complex::operator+ (complex &right) {
  35.   complex result ("Temp");
  36.   result.real_part = real_part + right.real_part;
  37.   result.imag_part = imag_part + right.imag_part;
  38.   return result;
  39. }
  40.  
  41. complex complex::operator- (complex &right) {
  42.   complex result ("Temp");
  43.   result.real_part = real_part - right.real_part;
  44.   result.imag_part = imag_part - right.imag_part;
  45.   return result;
  46. }
  47.  
  48. complex complex::operator* (complex &right) {
  49.   complex result ("Temp");
  50.   result.real_part = real_part * right.real_part -
  51.                      imag_part * right.imag_part;
  52.   result.imag_part = imag_part * right.real_part +
  53.                      real_part * right.imag_part;
  54.   return result;
  55. }
  56.  
  57. void complex::print(void) {
  58.   printf("  %s: %10.5f + %10.5fi\n",
  59.           name, real_part, imag_part);
  60. }
  61.  
  62. void main(void)
  63. {
  64.   printf("%s\n", HEADER);
  65.  
  66.   complex a("A"), b("B", 2.0, 3.0), c("C");
  67.  
  68.   a = b;
  69.   printf("A = B\n");
  70.   a.print(); b.print(); c.print();
  71.   a.set(5.0, -4.0);
  72.   printf("A = 5 - 4i\n");
  73.   a.print(); b.print(); c.print();
  74.   c = a + b;
  75.   printf("C = A + B\n");
  76.   a.print(); b.print(); c.print();
  77.   c = a - b;  
  78.   printf("C = A - B\n");
  79.   a.print(); b.print(); c.print();
  80.   c = a * b;
  81.   printf("C = A * B\n");
  82.   a.print(); b.print(); c.print();
  83. }
  84.